//
//  LoadViewController.m
//  LetsParty
//
//  Created by rimi on 15/9/17.
//  Copyright (c) 2015年 LetsPartyTeam. All rights reserved.
//

#import "CYYLoadViewController.h"
#import "CYYForgetPasswordViewController.h"
#import "CYYSignUpView.h"
#import "CYYLoadView.h"

enum{
    ChangeLoadButtonTag = 100,
    ChangeSignUpButtonTag,
    LoadButtonTag,
    ForgetPasswordButtonTag,
};
@interface CYYLoadViewController ()

@property (nonatomic, strong) UIScrollView * mainScrollView;//主滚动视图
@property (nonatomic, strong) UIImageView * backgroundImageView;
@property (nonatomic, strong) CYYLoadView * newLoadView;//登陆底图
@property (nonatomic, strong) CYYSignUpView * signUpView;//注册底图
@property (nonatomic, strong) UIButton * changeRegistButton;//注册切换按钮
@property (nonatomic, strong) UIButton * changeLoadButton;//登陆切换按钮
@property (nonatomic, strong) UIVisualEffectView * cEffectView;//模糊效果

- (void)initializeUserInterface;

@end

@implementation CYYLoadViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillHideNotification];
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillShowNotification];
    //清空密码
    self.newLoadView.passwordTextField.text = @"";
}

#pragma mark - private methods
- (void)initializeUserInterface{
    self.baseNavigationBar.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = COLOR_RGB(61, 142, 233, 1);
    [self.leftNavButton setImage:[UIImage imageNamed:@"iconfont-guanbi-white"] forState:UIControlStateNormal];
    [self.leftNavButton addTarget:self action:@selector(respondsToLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backgroundImageView];
    [self.backgroundImageView addSubview:self.mainScrollView];
    [self.backgroundImageView addSubview:self.leftNavButton];
    [self.mainScrollView addSubview:self.changeLoadButton];
    [self.mainScrollView addSubview:self.changeRegistButton];
    [self.mainScrollView addSubview:self.newLoadView];
    [self.mainScrollView addSubview:self.signUpView];
    self.signUpView.hidden = YES;
    [self.changeRegistButton addTarget:self action:@selector(respondsToChangeButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.changeLoadButton addTarget:self action:@selector(respondsToChangeButton:) forControlEvents:UIControlEventTouchUpInside];
    //登陆
    [self.newLoadView.loadButton addTarget:self action:@selector(respondsToButton:) forControlEvents:UIControlEventTouchUpInside];
    //忘记密码
    [self.newLoadView.forgetPasswordButton addTarget:self action:@selector(respondsToButton:) forControlEvents:UIControlEventTouchUpInside];
    //注册
    [self.signUpView.registButton addTarget:self action:@selector(respondsToRegistButton:) forControlEvents:UIControlEventTouchUpInside];
    self.newLoadView.loadButton.tag = LoadButtonTag;
    self.newLoadView.forgetPasswordButton.tag = ForgetPasswordButtonTag;
    //键盘处理
    self.newLoadView.passwordTextField.inputAccessoryView = [self customKeyboardToolbar];
    self.newLoadView.mobilePhoneTextField.inputAccessoryView = [self customKeyboardToolbar];
//    self.newLoadView.mobilePhoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.signUpView.nameTextField.inputAccessoryView = [self customKeyboardToolbar];
    self.signUpView.mobilePhoneTextField.inputAccessoryView = [self customKeyboardToolbar];
//    self.signUpView.mobilePhoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.signUpView.emailTextField.inputAccessoryView = [self customKeyboardToolbar];
    self.signUpView.firstPasswordTextField.inputAccessoryView = [self customKeyboardToolbar];
    self.signUpView.secondPasswordTextField.inputAccessoryView = [self customKeyboardToolbar];
}

//键盘uitoolbar
- (UIToolbar * )customKeyboardToolbar{
    UIToolbar * toolbar = [[UIToolbar alloc]init];
    toolbar.backgroundColor = [UIColor whiteColor];
    toolbar.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 35), YES);
    toolbar.barTintColor = [UIColor whiteColor];
    //隐藏按钮
    UIBarButtonItem * spaceBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    spaceBarButtonItem.width = 200;
    UIBarButtonItem * rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-bohaojianpanshouqi"] style:UIBarButtonItemStylePlain target:self action:@selector(respondsToDoneButton)];
    rightBarButtonItem.tintColor = [UIColor darkGrayColor];
    toolbar.items = @[spaceBarButtonItem,rightBarButtonItem];
    return toolbar;
}

- (void)alterViewWithMessage:(NSString *)message{
    UIAlertController * alterViewController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alterViewController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [alterViewController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alterViewController animated:YES
                                completion:nil];
}

- (UIButton *)haveButtonWithFrame:(CGRect)frame title:(NSString *)title{
    //设置登陆button
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"iconfont-hengxian"] forState:UIControlStateSelected];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 30, 0);
    button.imageEdgeInsets = UIEdgeInsetsMake(30, 60, 0, 0);
    return button;
}

//判断密码
- (BOOL)judgePassword:(NSString *)string{
    //6~16位密码(字母数字下划线)
    NSString * regularSring = @"^\\w{6,16}$";
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"self matches %@",regularSring];
    //返回值为YES：表明密码不符合要求
    return ![predicate evaluateWithObject:string];
}

//判断是否为空
- (BOOL)judgeInputeInfoIsNil:(NSArray *)array{
    //返回值为YES：存在为空的对象
    return [array containsObject:@""];
}
//判断用户名 字母和汉字
- (BOOL)judgeUsername:(NSString *)string{
    NSString * regularString = @"^[a-zA-Z\u4E00-\u9FA5]+$";
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"self matches %@",regularString];
    //返回值为YES：表明用户名不符合要求
    return ![predicate evaluateWithObject:string];
}

- (void)clearRegisterInfo{
    self.newLoadView.mobilePhoneTextField.text = self.signUpView.mobilePhoneTextField.text;
    self.newLoadView.passwordTextField.text = self.signUpView.secondPasswordTextField.text;
    self.signUpView.emailTextField.text = @"";
    self.signUpView.nameTextField.text = @"";
    self.signUpView.mobilePhoneTextField.text = @"";
    self.signUpView.firstPasswordTextField.text = @"";
    self.signUpView.secondPasswordTextField.text = @"";
}

//登陆出错的动画
- (void)loadFailShakeAnimationByWhichView:(UIView *)view{
    CAKeyframeAnimation * cKeyAnimation = [CAKeyframeAnimation animation];
    cKeyAnimation.keyPath = @"position.x";
    cKeyAnimation.repeatCount = 2;
    cKeyAnimation.values = @[@(155 * DHFlexibleHorizontalMutiplier()),@(160 * DHFlexibleHorizontalMutiplier()),@(165 * DHFlexibleHorizontalMutiplier())];
    cKeyAnimation.duration = 0.1;
    [view.layer addAnimation:cKeyAnimation forKey:@""];
}

#pragma mark - responds event
- (void)respondsToLeftButton:(UIButton *)button{
    if (![[UserModel defaultUser] isAlreadyLoad]) {
        [[[ControllerManager sharedManager] mainTabController] goToViewWithIndex:0];
        [[[ControllerManager sharedManager] mainTabController] dismissViewControllerAnimated:YES completion:nil];
    }else{
        [[[ControllerManager sharedManager] mainTabController]  dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)respondsToChangeButton:(UIButton *)button{
    switch (button.tag) {
        case ChangeSignUpButtonTag:{
            button.selected = YES;
            self.changeLoadButton.selected = NO;
            self.newLoadView.hidden = YES;
            self.signUpView.hidden = NO;
        }
            break;
        case ChangeLoadButtonTag:{
            button.selected = YES;
            self.changeRegistButton.selected = NO;
            self.newLoadView.hidden = NO;
            self.signUpView.hidden = YES;
        }
            break;
    }
}

- (void)respondsToHidePassword:(UIButton *)button{
    button.selected = !button.selected;
    self.newLoadView.passwordTextField.secureTextEntry = (button.selected ? NO : YES);
}

- (void)respondsToButton:(UIButton *)button{
    CYYForgetPasswordViewController * forgetVC = [[CYYForgetPasswordViewController alloc]init];
    switch (button.tag) {
        case LoadButtonTag:{
            __weak typeof(self) myVC = self;
            [CYYNetWorkManager signInWithmMobilePhoneNumber:myVC.newLoadView.mobilePhoneTextField.text password:myVC.newLoadView.passwordTextField.text sucessSignIn:^(BmobUser *user) {
                [myVC respondsToLeftButton:myVC.leftNavButton];
            } fail:^(NSError *error) {
                [myVC loadFailShakeAnimationByWhichView:myVC.newLoadView.mobilePhoneTextField];
                [myVC loadFailShakeAnimationByWhichView:myVC.newLoadView.passwordTextField];
            }];
        }
            break;
        case ForgetPasswordButtonTag:
            [self.navigationController pushViewController:forgetVC animated:YES];
            break;
    }
}

- (void)respondsToRegistButton:(UIButton *)button{
    //判断是否为空
    if ([self judgeInputeInfoIsNil:@[self.signUpView.nameTextField.text,self.signUpView.mobilePhoneTextField.text,self.signUpView.firstPasswordTextField.text,self.signUpView.secondPasswordTextField.text]]) {
        [self alterViewWithMessage:@"输入的信息不能为空"];
        return;
    }
    //判断用户名
    if ([self judgeUsername:self.signUpView.nameTextField.text]) {
        [self alterViewWithMessage:@"用户名只能是汉字、字母"];
        return;
    }
    //判断密码是否为字母、数字、下划线
    if ([self judgePassword:self.signUpView.firstPasswordTextField.text]) {
        [self alterViewWithMessage:@"密码只能是6~16位的字母、数字、下划线"];
        return;
    }
    //如果两次输入的密码不一样
    if (![self.signUpView.firstPasswordTextField.text isEqualToString:self.signUpView.secondPasswordTextField.text]) {
        [self alterViewWithMessage:@"两次输入的密码不一致"];
        return;
    }
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager signUpWithName:myVC.signUpView.nameTextField.text
                    mobilePhoneNumber:myVC.signUpView.mobilePhoneTextField.text
                             password:myVC.signUpView.secondPasswordTextField.text
                                email:myVC.signUpView.emailTextField.text
                               sucess:^(NSString *sucessString) {
                                   [myVC respondsToChangeButton:myVC.changeLoadButton];
                                   [myVC alterViewWithMessage:sucessString];
                                   [myVC clearRegisterInfo];
                               } fail:^(NSError *error) {
                                   if (error.code == 209) {
                                      [myVC alterViewWithMessage:@"手机号已经存在"];
                                   }else if(error.code == 301){
                                       [myVC alterViewWithMessage:@"手机号或邮箱不合法"];
                                   }else if(error.code == 203){
                                       [myVC alterViewWithMessage:@"输入的邮箱已经存在"];
                                   }else{
                                       [myVC alterViewWithMessage:@"输入的信息有误"];
                                   }
                               }];
}


- (void)keyboardWillShow:(NSNotification *)notification{
    //获得键盘高度
    //    [(NSValue *)[notification.userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height
    self.mainScrollView.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 568 -  150), NO);
    
}

- (void)keyboardWillHiden:(NSNotification *)notification{
    self.mainScrollView.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 568), NO);
}

//处理键盘隐藏事件
- (void)respondsToDoneButton{
    [self.view endEditing:YES];
}

#pragma mark - getter
-(UIScrollView *)mainScrollView{
    if (!_mainScrollView) {
        _mainScrollView = ({
            UIScrollView * scrollView = [[UIScrollView alloc]init];
            scrollView.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 568), NO);
            scrollView.contentSize = DHFlexibleSize(CGSizeMake(320, 568), NO);
            scrollView;
        });
    }
    return _mainScrollView;
}

- (UIImageView *)backgroundImageView{
    if (!_backgroundImageView) {
        _backgroundImageView = ({
            UIImageView * backgroundImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loadview-1"]];
            backgroundImageView.frame = self.view.frame;
            [backgroundImageView addSubview:self.cEffectView];
            backgroundImageView.userInteractionEnabled = YES;
            backgroundImageView;
        });
    }
    return _backgroundImageView;
}

- (CYYLoadView *)newLoadView{
    if (!_newLoadView) {
        _newLoadView = ({
            CYYLoadView * cView = [[CYYLoadView alloc]init];
            cView.frame = DHFlexibleFrame(CGRectMake(0, 150, 320, 300), NO);
            cView;
        });
    }
    return _newLoadView;
}

- (CYYSignUpView *)signUpView{
    if (!_signUpView) {
        _signUpView = ({
            CYYSignUpView * cView = [[CYYSignUpView alloc]init];
            cView.frame = DHFlexibleFrame(CGRectMake(0, 120, 320, 300), NO);
            cView;
        });
    }
    return _signUpView;
}

- (UIButton *)changeRegistButton{
    if (!_changeRegistButton) {
        _changeRegistButton = ({
            [self haveButtonWithFrame:DHFlexibleFrame(CGRectMake(160, 70 , 140, 60),NO) title:@"注册"];
        });
        _changeRegistButton.tag = ChangeSignUpButtonTag;
    }
    return _changeRegistButton;
}

- (UIButton *)changeLoadButton{
    if (!_changeLoadButton) {
        _changeLoadButton = ({
            [self haveButtonWithFrame:DHFlexibleFrame(CGRectMake(20, 70 , 140, 60),NO) title:@"登陆"];
        });
        _changeLoadButton.tag = ChangeLoadButtonTag;
        self.changeLoadButton.selected = YES;
    }
    return _changeLoadButton;
}

- (UIVisualEffectView *)cEffectView{
    if (!_cEffectView) {
        _cEffectView = ({
            UIBlurEffect * cBlurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
            UIVisualEffectView * cEffectView = [[UIVisualEffectView alloc]initWithEffect:cBlurEffect];
            cEffectView.frame = self.view.frame;
            cEffectView.backgroundColor = COLOR_RGB(80, 134, 234, 0.6);
            cEffectView;
        });
    }
    return _cEffectView;
}

@end
